package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.User;
import com.itheima.health.service.UserService;
import com.itheima.health.vo.LoginParam;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author spt
 * @description
 **/
@RestController
@RequestMapping("/user")
@Slf4j
@Api(tags = "用户模块接口")
public class UserController {
    @Autowired
    private UserService userService;

    @Value("${health.salt}")
    private String salt;

    /**
     * 根据用户名和密码登录
     */
    @ApiOperation("用户登录")
    @PostMapping("/login")
    public Result login(@RequestBody LoginParam param) {
        log.info("[登录]data:{}",param);
        //rpc调用查询用户信息
        User user = userService.findByUsername(param.getUsername());
        //用户不存
        if(user==null){
            return new Result(false, MessageConst.LOGIN_FAIL);
        }

        //密码加密方案1：MD5+盐（用户公共盐）- 公共盐在配置文件中配好，所有用户用到的盐都是一样的
        //String password = DigestUtils.md5DigestAsHex((param.getPassword()+salt).getBytes());

        //密码加密方案1：MD5+盐（用户私有盐） - 用户表需要再设计一个字段salt，用于新增用户时保存每个用户密码加密用到的盐，所有用户用到的盐都不一样
        //String password = DigestUtils.md5DigestAsHex((param.getPassword()+user.getSalt()).getBytes());
        //boolean result = user.getPassword().equalsIgnoreCase(password);

        //密码加密方案2：BCrypt
        boolean result = BCrypt.checkpw(param.getPassword(),user.getPassword());
        if (!result) {
            log.info("[登录]失败，user:{}",param.getUsername());

            return new Result(false, MessageConst.LOGIN_FAIL);
        }
        //模拟用户登录成功
        log.info("[登录]成功，user:{}",user.getUsername());
        return new Result(true, MessageConst.LOGIN_SUCCESS);
    }
}
